package com.example.data.factory.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.data.factory.common.common.StringConstant;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Map;
@Component
public class JwtUtil {
    private static final String SECRET = "1234"; // 确保这是安全的！建议不要硬编码
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 生成token
     */
    public String createToken(Map<String, String> subject) {
//        Date date = new Date(System.currentTimeMillis() + 3600 * 1000); // 1小时有效期
        JWTCreator.Builder builder = JWT.create();
        subject.forEach(builder::withClaim);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1); // 设置默认过期时间
        builder.withExpiresAt(calendar.getTime());  // 指定过期时间
        return builder.sign( Algorithm.HMAC256(SECRET));
    }
    /**
     * 校验token并检查是否在黑名单中
     */
    public DecodedJWT verifyToken(String token) {
        // 检查 token 是否在黑名单中
        if (Boolean.TRUE.equals ( redisTemplate.hasKey ( "blacklist:" + token ) )) {
            throw new RuntimeException( StringConstant.TOKENISNOUSE);
        }
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }
    /**
     * 获取token信息
     */
    public Map<String, Claim> getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token).getClaims();
    }
    /**
     * 将 token 加入黑名单
     */
    public void addToBlacklist(String token) {
        redisTemplate.opsForValue().set("blacklist:" + token, "true");
    }
}